/**
 * @Author 韦建韩
 * @Date 2022/5/6
 */
package com.example.devops.web.controller.applicationAdmin;

import com.example.devops.Manage.ProjectPublishCenter;
import com.example.devops.entity.common.Result;
import com.example.devops.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
@ServerEndpoint("/api/project_publish/publishProcess/{mirrorId}/{userId}/{branch}")
public class ProjectPublishProcessServer {
    Logger logger = LoggerFactory.getLogger(ProjectPublishProcessServer.class);
    private static ProjectPublishCenter projectPublishCenter;

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     */
    private static ConcurrentHashMap<String, ProjectPublishProcessServer> webSocketMap = new ConcurrentHashMap<>();
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收projectId
     */
    private String mirrorId = "";
    private String userId = "";
    private String branch = "";


    @Autowired
    public void setprojectPublishCenter(ProjectPublishCenter projectPublishCenter) {
        this.projectPublishCenter = projectPublishCenter;
    }

    /**
     * 连接建立成
     * 功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("mirrorId") String mirrorId, @PathParam("userId") String userId, @PathParam("branch") String branch) throws IOException {
      try {
          this.session = session;
          this.mirrorId = mirrorId;
          this.userId = userId;
          this.branch = branch;
          logger.info("inter websocket,mirrorId:{},userId:{},branch:{}", mirrorId, userId, branch);

          if (webSocketMap.containsKey(mirrorId)) {
              //项目正在发布中
              Result result = Result.doCreate();
              result.setData("项目正在发布中");
          } else {
              webSocketMap.put(mirrorId, this);
              logger.info("connect success,mirrorId:{},userId:{},branch:{}", mirrorId, userId, branch);
              projectPublishCenter.run(mirrorId, userId, branch);
          }
      }catch (Exception e){
          logger.error("error:",e);
          this.session.close(new CloseReason(CloseReason.CloseCodes.NO_STATUS_CODE,e.getMessage()));
      }

//        log.info("用户连接:"+projectId+",当前在线人数为:" + getOnlineCount());
//        sendMessage("连接成功");
    }

    //主动关闭连接
    public static void close(String mirrorId, String message) throws IOException {
        if (webSocketMap.containsKey(mirrorId)) {
            ProjectPublishProcessServer projectPublishProcessServer = webSocketMap.get(mirrorId);
            CloseReason closeReason = new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, message);
            projectPublishProcessServer.session.close(closeReason);
        } else {
            throw new CustomException("webSocket主动关闭失败");
        }
    }

    /**
     * 收到客户端消
     * 息后调用的方法
     *
     * @param message 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("用户消息:" + mirrorId + ",报文:" + message);
        //可以群发消息
        //消息保存到数据库、redis
        if (Strings.isNotBlank(message)) {
        /*    try {
                //解析发送的报文
//                JSONObject jsonObject = JSON.parseObject(message);
                //追加发送人(防止串改)
//                jsonObject.put("fromprojectId",this.projectId);
//                String toprojectId=jsonObject.getString("toprojectId");
                //传送给对应toprojectId用户的websocket
                if(StringUtils.isNotBlank(toprojectId)&&webSocketMap.containsKey(toprojectId)){
                    webSocketMap.get(toprojectId).sendMessage(message);
                }else{
                    //否则不在这个服务器上，发送到mysql或者redis
                    log.error("请求的projectId:"+toprojectId+"不在该服务器上");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            */

        }
    }

    @OnClose
    public void onClose() {
        webSocketMap.remove(this.mirrorId);
        System.out.println("连接关闭");
    }

    @OnError
    public void onError(Session session, Throwable error) {

        log.error("用户错误:" + this.mirrorId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务
     * 器主动推送
     */
    public void sendMessageJson(Result result) {
        try {
            this.session.getBasicRemote().sendObject(result);

        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    public void sendMessageString(String s) {
        try {
            this.session.getBasicRemote().sendText(s);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送自定
     * 义消息
     **/
    public static void sendInfo(String message, String mirrorId) {
        log.info("发送消息到:" + mirrorId + "，报文:" + message);
        if (Strings.isNotBlank(mirrorId) && webSocketMap.containsKey(mirrorId)) {
            webSocketMap.get(mirrorId).sendMessageString(message);

        } else {
            log.error("用户" + mirrorId + ",不在线！");
        }
    }


}
